<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="tabs">
      <div
        class="tabs-item"
        :class="{ active: currentTab === index }"
        v-for="(item, index) in tabs"
        :key="index"
        @click="handleChangeTab(item, index)"
      >
        {{ item }}
      </div>
    </div>
    <div class="body">
      <BaseInfo
        ref="baseInfoRef"
        :isEdit="isEdit"
        :isDetail="isDetail"
        :detailInfo="baseInfo"
        :baseInfoData="baseInfoData"
        v-show="currentTab === 0"
      />

      <!-- 项目计划查看 -->
      <PlanInfo
        ref="planInfoRef"
        v-if="isDetail"
        :detailInfo="planInfo"
        v-show="currentTab === 1"
      />

      <!-- 项目计划编辑 -->
      <PlanInfoEdit
        ref="planInfoEditRef"
        v-if="!isDetail"
        :isDetail="isDetail"
        :detailInfo="planInfo"
        v-show="currentTab === 1"
      />

      <!-- 项目进展查看 -->
      <ProcessInfo
        ref="processInfoRef"
        v-if="isDetail"
        :nodeList="nodeList"
        :processList="processList"
        :fixedTotal="fixedTotal"
        :planTotal="planTotal"
        v-show="currentTab === 2"
      />

      <!-- 项目进展编辑 -->
      <ProcessInfoEdit
        ref="processInfoEditRef"
        :isEdit="isEdit"
        v-if="!isDetail"
        :isDetail="isDetail"
        :nodeList="nodeList"
        :yearTotalList="yearTotalList"
        :seasonTotalList="seasonTotalList"
        :processList="processList"
        :fixedTotal="fixedTotal"
        :planTotal="planTotal"
        v-show="currentTab === 2"
      />

      <BidSectionInfo
        ref="yearInfoRef"
        :isDetail="isDetail"
        :yearList="yearList"
        :detailInfo="yearInfo"
        :baseInfo="baseInfo"
        :sectionList="sectionList"
        v-show="currentTab === 4 && sectionList.length"
        @changeYearPlanInvestment="
          handleChangeYearPlanInvestment
        "
      />

      <!--      项目进度-->
      <ProjectData
        v-show="currentTab === 3"
        :currentTab="currentTab"
        :isDetail="isDetail"
        :isEdit="isEdit"
        :detailInfo="baseInfoData"
        ref="projectDataRef"
      />
    </div>
    <div class="line" v-if="!isDetail">
      <el-button
        @click="saveInfo"
        class="save-btn"
        :loading="btnLoding"
        >保存
      </el-button>
    </div>
    <div class="line" v-else>
      <el-button @click="goList" class="save-btn"
        >返回
      </el-button>
    </div>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import BaseInfo from './components/baseInfo.vue'
import PlanInfo from './components/planInfo.vue'
import ProcessInfo from './components/processInfo.vue'
import BidSectionInfo from './components/bidSectionInfo.vue'
import UploadShpFile from '../components/uploadShpFile.vue'
import PlanInfoEdit from './components/planInfoEdit.vue'
import ProcessInfoEdit from './components/processInfoEdit.vue'
import ProjectData from './components/projectData.vue'

import {
  queryConstructionBaseInfo,
  editConstructionInfo,
  uploadFileById
} from '@/api/dataManagement'
import dayjs from 'dayjs'
import cloneDeep from 'lodash/cloneDeep'

export default {
  props: {
    pkid: String,
    title: String,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    ProjectData,
    Breadcrumb,
    BaseInfo,
    PlanInfo,
    ProcessInfo,
    BidSectionInfo,
    UploadShpFile,
    PlanInfoEdit,
    ProcessInfoEdit
  },
  data() {
    return {
      tabs: [],
      currentTab: 0,
      loading: false,
      isEditReady: false,
      isEditChanged: false,
      btnLoding: false,
      resultArr: [],
      formArr: [
        'baseInfoRef',
        'yearInfoRef',
        'planInfoRef',
        'processInfoRef'
      ],
      baseInfo: {},
      planInfo: [],
      yearInfo: [],
      yearList: [],
      nodeList: [],
      processList: [],
      redAreaTotal: 0,
      buildAreaTotal: 0,
      sectionList: [],
      fixedTotal: null,
      planTotal: null,
      yearTotalList: [],
      seasonTotalList: [],
      baseInfoData: {},
      leaveTimer: null
    }
  },
  created() {
    this.isDetail
      ? (this.tabs = [
          '项目信息',
          '项目计划',
          '项目进度（区平台）',
          '项目进度',
          '项目标段'
        ])
      : (this.tabs = [
          '项目信息',
          '项目计划',
          '项目进度（区平台）',
          '项目进度'
        ])
  },
  computed: {
    titles() {
      return [this.title]
    }
  },
  watch: {
    sectionList(val) {
      val.length && this.isDetail
        ? (this.tabs = [
            '项目信息',
            '项目计划',
            '项目进度（区平台）',
            '项目进度',
            '项目标段'
          ])
        : (this.tabs = [
            '项目信息',
            '项目计划',
            '项目进度（区平台）',
            '项目进度'
          ])
    }
  },
  mounted() {
    if (this.pkid) {
      // this.isDetail = false
      this.getBaseInfo()
    }
    this.isEdit
      ? (this.currentTab = 3)
      : (this.currentTab = 0)
  },
  beforeRouteLeave(to, from, next) {
    this.isEditChanged =
      this.$refs.baseInfoRef?.isBasicFormChanged ||
      this.$refs.planInfoEditRef?.isPlanInfoChanged ||
      this.$refs.processInfoEditRef?.isProcessInfoChanged ||
      this.$refs.projectDataRef?.isProjectDataChanged
    if (this.isDetail || !this.isEditChanged) {
      next()
    } else {
      if (to.path !== '/login') {
        this.leaveTimer = setTimeout(() => {
          this.$confirm('信息未保存，确认退出?', '注意', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              next()
            })
            .catch(() => {
              next(false)
            })
        }, 100)
      } else {
        if (this.leaveTimer) {
          clearTimeout(this.leaveTimer)
        }
        next(true)
      }
    }
  },
  methods: {
    getBaseInfo() {
      this.loading = true
      queryConstructionBaseInfo(this.pkid)
        .then((res) => {
          if (res.success) {
            this.baseInfo = res.data.baseMess
            if (
              !this.baseInfo.fundBuildSource ||
              (!['政府投资', '其他'].includes(
                this.baseInfo.fundBuildSource
              ) &&
                !this.baseInfo.landingMethod)
            ) {
              this.currentTab = 0
            }
            this.baseInfoData = cloneDeep(res.data)
            if (this.baseInfo.year.length) {
              this.baseInfo.year =
                this.baseInfo.year.split(',')
            }
            this.baseInfo.processDetailRelList =
              res.data.processDetailRelList
            this.planInfo = res.data.year
            this.nodeList = res.data.node
            this.processList = res.data.process
            this.fixedTotal =
              Number(res.data.year[0]?.fixedTotal) || 0
            this.planTotal =
              Number(res.data.year[0]?.planTotal) || 0

            if (this.isEdit) {
              this.$refs.baseInfoRef.setInfoReady()
              this.$refs.planInfoEditRef.setInfoReady()
              this.$refs.processInfoEditRef.setInfoReady()
            }
            // this.redAreaTotal = 0
            // this.buildAreaTotal = 0

            // res.data.sectionVo.forEach((item) => {
            //   if (item.section.redArea) {
            //     this.redAreaTotal += Number(
            //       item.section.redArea
            //     )
            //   }

            //   if (item.section.buildTotalArea) {
            //     this.buildAreaTotal += Number(
            //       item.section.buildTotalArea
            //     )
            //   }
            // })

            this.sectionList = res.data.sectionVo
          } else {
            this.$message.error(res.message)
          }
          this.loading = false
        })
        .catch((err) => {
          this.$message.error(err)
          this.loading = false
        })
    },
    goList() {
      this.$router.push({
        path: '/dataManagement/projectManagement/constructProjectInfo/list',
        query: { refresh: Date.now() }
      })
    },
    // 切换tab
    handleChangeTab(item, index) {
      // if (index !== 0) {
      //   if (!this.yearList || this.yearList.length === 0) {
      //     this.$message.warning('请选择项目年度')
      //     return
      //   }
      // }
      console.log('this.currentTab ', this.currentTab)
      console.log(item, '', index)
      if (
        this.currentTab === 0 &&
        index !== this.currentTab
      ) {
        this.$refs.baseInfoRef.validateForm(
          (res, errorFields) => {
            if (res) {
              if (item === '项目进度（区平台）') {
                this.currentTab = index
                this.yearTotalList =
                  this.$refs.planInfoEditRef.getYearList()
                this.seasonTotalList =
                  this.$refs.planInfoEditRef.getSeasonList()
              } else if (item === '项目进度') {
                this.currentTab = index
                this.$refs.projectDataRef.initData(
                  this.$refs.baseInfoRef.basicForm
                )
              } else {
                this.currentTab = index
              }
            } else {
              const firstError = Object.keys(errorFields)[0]
              this.$message.error(
                errorFields[firstError][0].message ||
                  '请填写必填项'
              )
            }
          }
        )
      } else {
        console.log('cur tab: ', this.currentTab, item)
        this.currentTab = index
        if (item === '项目进度（区平台）') {
          this.yearTotalList =
            this.$refs.planInfoEditRef.getYearList()
          this.seasonTotalList =
            this.$refs.planInfoEditRef.getSeasonList()
        } else if (item === '项目进度') {
          this.$refs.projectDataRef.initData(
            this.$refs.baseInfoRef.basicForm
          )
        }
        // if (item === '项目进度') {
        //   this.$refs.projectDataRef.initData(
        //     this.$refs.baseInfoRef.basicForm
        //   )
        // }
      }
    },

    // 修改年度投资
    handleChangeYearPlanInvestment(year, val) {
      this.yearPlanInvestment[year] = val || 0
    },

    getProcessInfo() {
      const newProcessId =
        this.$refs.baseInfoRef.blankTemplateInfo[0]
          ?.processId
      const curProcessId =
        this.$refs.projectDataRef.templateInfo[0]?.processId
      console.log('newProcessId', newProcessId)
      console.log('curProcessId', curProcessId)
      if (newProcessId === curProcessId) {
        return {
          processNodeRels:
            this.$refs.projectDataRef.templateInfo,
          enterpriseInvestmentRels:
            this.$refs.projectDataRef.elementInfo
        }
      } else {
        return {
          processNodeRels:
            this.$refs.baseInfoRef.blankTemplateInfo,
          enterpriseInvestmentRels:
            this.$refs.baseInfoRef.blankElementList
        }
      }
    },

    // 点击保存
    saveInfo() {
      this.$refs.baseInfoRef.validateForm(
        (res, errorFields) => {
          if (!res) {
            const firstError = Object.keys(errorFields)[0]
            this.$message.error(
              errorFields[firstError][0].message ||
                '请填写必填项'
            )
            return
          }

          const one =
            this.$refs.projectDataRef.templateInfo.find(
              (e) => {
                if (
                  !['已办结', '提前交地'].includes(
                    e.nodeStatus
                  )
                ) {
                  e.nodeFinishTime = ''
                }
                return e.processId == '1' &&
                  e.nodeName == '土地批文'
                  ? false
                  : ['已办结', '提前交地'].includes(
                      e.nodeStatus
                    ) && !e.nodeFinishTime
              }
            )
          if (one) {
            this.loading = false
            return this.$message.error(
              `请输入【${one.nodeName}】的实际完成时间`
            )
          }

          if (res) {
            const process =
              this.$refs.processInfoEditRef.getProcessList()

            const isInvalid = process.some(
              (item) => !item.year || !item.month
            )

            if (isInvalid) {
              this.$message.warning(
                '请填写项目进度每一项的年份和月份'
              )
              return
            }

            this.loading = true

            const baseInfo = this.$refs.baseInfoRef

            const form = baseInfo.getFormData()
            form.year = form.year.length
              ? form.year.join(',')
              : ''
            form.planStartTime = this.setDateFormat(
              form.planStartTime
            )
            form.planEndTime = this.setDateFormat(
              form.planEndTime
            )
            form.useTime = this.setDateFormat(form.useTime)

            // if (
            //   ['政府投资', '其他'].includes(
            //     form.fundBuildSource
            //   )
            // ) {
            //   form.landingMethod = ''
            // }

            const years =
              this.$refs.planInfoEditRef.getYearList()
            const seasons =
              this.$refs.planInfoEditRef.getSeasonList()
            const nodes =
              this.$refs.processInfoEditRef.getNodeList()
            const effects = baseInfo.getEffectList()

            const currentUpload = effects.filter(
              (i) => !i.pkid
            )
            const isUploadImage = effects
              .filter((i) => i.pkid)
              .map((item) => item.pkid)

            // 处理进度图片上传
            const progressPromises =
              form.processDetailRelList.map(
                async (item) => {
                  if (
                    item.progressImages &&
                    item.progressImages.length > 0
                  ) {
                    // 找出需要上传的图片（即包含 raw 且是 File 类型的）
                    const newImages =
                      item.progressImages.filter(
                        (img) => img.raw instanceof File
                      )

                    // 构建上传请求
                    const uploadPromises = newImages.map(
                      (img) => {
                        const formData = new FormData()
                        formData.append('file', img.raw)
                        return uploadFileById(formData)
                      }
                    )

                    if (uploadPromises.length > 0) {
                      // 等待上传完成
                      const uploadResults =
                        await Promise.all(uploadPromises)

                      let uploadIndex = 0

                      // 合并所有图片的 ID（已上传 + 新上传）
                      const imageIds = item.progressImages
                        .map((img) => {
                          if (img.raw instanceof File) {
                            // 新上传的，从 uploadResults 中取对应返回 ID
                            const result =
                              uploadResults[uploadIndex]
                            uploadIndex++
                            return result?.data || null
                          } else if (img.pkid) {
                            // 已上传的，直接取 pkid
                            return img.pkid
                          }
                          return null
                        })
                        .filter(Boolean)

                      item.progressPicture =
                        imageIds.join(',')
                    } else {
                      // 没有新上传，只处理已有图片
                      const imageIds = item.progressImages
                        .filter(
                          (img) => img.filePath || img.url
                        )
                        .map((img) => img.pkid || null)
                        .filter(Boolean)

                      item.progressPicture =
                        imageIds.join(',')
                    }
                  }

                  return item
                }
              )

            // 处理项目效果图上传
            const uploadPromises = currentUpload.map(
              (file) => {
                const image = new FormData()
                image.append('file', file)
                return uploadFileById(image)
              }
            )
            // 项目进度的字段模板 id
            // processNodeRels:this.$refs.projectDataRef.processNodeRels,
            //   constructionElements:this.$refs.projectDataRef.constructionElements,
            //   constructionElementsValue:this.$refs.projectDataRef.constructionElementsValue,
            // 先处理进度图片
            Promise.all(progressPromises)
              .then(() => {
                // 再处理效果图
                if (uploadPromises.length > 0) {
                  return Promise.all(uploadPromises)
                }
                return Promise.resolve([])
              })
              .then((results) => {
                if (results.length > 0) {
                  const allSuccess = results.every(
                    (res) => res.success
                  )

                  if (!allSuccess) {
                    this.$message.error('部分图片上传失败')
                    return
                  }

                  const imageArr = results.map(
                    (item) => item.data
                  )
                  form.effectPicture = imageArr
                    .concat(isUploadImage)
                    .join(',')
                }
                form.constructionElements =
                  this.$refs.projectDataRef.constructionElements.join()
                form.constructionElementsValue = this.$refs
                  .projectDataRef.isOtherChecked
                  ? this.$refs.projectDataRef
                      .constructionElementsValue
                  : ''

                const {
                  processNodeRels,
                  enterpriseInvestmentRels
                } = this.getProcessInfo()

                const params = {
                  processNodeRels,
                  enterpriseInvestmentRels,
                  baseMess: form,
                  year: this.setYearData(years, seasons),
                  node: nodes.map((item) => {
                    return {
                      ...item,
                      planStartTime: this.setDateFormat(
                        item.planStartTime
                      ),
                      planEndTime: this.setDateFormat(
                        item.planEndTime
                      ),
                      realEndTime: this.setDateFormat(
                        item.realEndTime
                      )
                    }
                  }),
                  process: process.map((item) => {
                    return {
                      ...item,
                      joinTime: this.setDateFormat(
                        item.joinTime
                      )
                    }
                  }),
                  processDetailRelList:
                    form.processDetailRelList
                }

                editConstructionInfo(params)
                  .then((res) => {
                    if (res.success) {
                      this.loading = false
                      this.$refs.baseInfoRef.isBasicFormChanged = false
                      this.$refs.planInfoEditRef.isPlanInfoChanged = false
                      this.$refs.processInfoEditRef.isProcessInfoChanged = false
                      this.$refs.projectDataRef.isProjectDataChanged = false
                      this.isEditChanged = false
                      this.$message.success('保存成功')
                      this.$router.push({
                        path: '/dataManagement/projectManagement/constructProjectInfo/list',
                        query: { refresh: Date.now() }
                      })
                    } else {
                      this.loading = false
                      this.$message.error(
                        res.message || '保存失败'
                      )

                      form.year = form.year.split(',')
                    }
                  })
                  .catch((err) => {
                    this.loading = false
                    this.$message.error('保存失败')
                    console.error(err)
                  })
              })
              .catch((err) => {
                this.loading = false
                this.$message.error('图片上传出错')
                console.error(err)
              })
          }
        }
      )
    },

    setYearData(years, seasons) {
      const yearMap = new Map()

      years.forEach((item) => {
        yearMap.set(item.year, { ...item })
      })

      seasons.forEach((item) => {
        if (yearMap.has(item.year)) {
          Object.assign(yearMap.get(item.year), item)
        } else {
          yearMap.set(item.year, { ...item })
        }
      })

      const merged = Array.from(yearMap.values())

      const arr = []
      merged.forEach((item) => {
        const obj = {
          pkid: item.pkid,
          year: item.year,
          planTotal: item.planTotal ? item.planTotal : '',
          planOne: item.month1 ? item.month1 : '',
          planTwo: item.month2 ? item.month2 : '',
          planThree: item.month3 ? item.month3 : '',
          planFour: item.month4 ? item.month4 : '',
          planFive: item.month5 ? item.month5 : '',
          planSix: item.month6 ? item.month6 : '',
          planSeven: item.month7 ? item.month7 : '',
          planEight: item.month8 ? item.month8 : '',
          planNine: item.month9 ? item.month9 : '',
          planTen: item.month10 ? item.month10 : '',
          planEleven: item.month11 ? item.month11 : '',
          planTwelve: item.month12 ? item.month12 : '',
          fixedTotal: item.fixedTotal
            ? item.fixedTotal
            : '',
          fixedOne: item.season1 ? item.season1 : '',
          fixedTwo: item.season2 ? item.season2 : '',
          fixedThree: item.season3 ? item.season3 : '',
          fixedFour: item.season4 ? item.season4 : '',
          fixedOneFirst: item.fixedOneFirst
            ? item.fixedOneFirst
            : '',
          fixedOneSecond: item.fixedOneSecond
            ? item.fixedOneSecond
            : '',
          fixedTwoFirst: item.fixedTwoFirst
            ? item.fixedTwoFirst
            : '',
          fixedTwoSecond: item.fixedTwoSecond
            ? item.fixedTwoSecond
            : '',
          fixedThreeFirst: item.fixedThreeFirst
            ? item.fixedThreeFirst
            : '',
          fixedThreeSecond: item.fixedThreeSecond
            ? item.fixedThreeSecond
            : '',
          fixedFourFirst: item.fixedFourFirst
            ? item.fixedFourFirst
            : '',
          fixedFourSecond: item.fixedFourSecond
            ? item.fixedFourSecond
            : ''
        }
        arr.push(obj)
      })
      return arr
    },

    setDateFormat(date) {
      if (date) {
        return dayjs(date).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },

    handleSubmit() {
      // 处理图片数据
      const processedData = {
        ...this.form,
        progressImages: []
      }
      // 1. 构建 filePath 到 pkid 的映射
      const filePathToPkid = {}
      if (
        this.form.resourceFileInfos &&
        Array.isArray(this.form.resourceFileInfos)
      ) {
        this.form.resourceFileInfos.forEach((info) => {
          if (info.filePath && info.pkid) {
            filePathToPkid[info.filePath] = info.pkid
          }
        })
      }
      // 2. 处理 progressImages
      const imageIds = []
      if (
        this.form.progressImages &&
        Array.isArray(this.form.progressImages)
      ) {
        this.form.progressImages.forEach((img) => {
          if (img.filePath) {
            // 已上传图片，从 resourceFileInfos 中获取 pkid
            const pkid = filePathToPkid[img.filePath]
            if (pkid) {
              imageIds.push(pkid)
            }
            processedData.progressImages.push({
              filePath: img.filePath,
              url: `${STATIC_FILE_URL}${img.filePath}`,
              isUploaded: true
            })
          } else if (img.raw && img.raw.uid) {
            // 新上传图片
            imageIds.push(img.raw.uid.toString())
            const file = img.raw
            const url = img.url || URL.createObjectURL(file)
            processedData.progressImages.push({
              url,
              raw: file,
              isUploaded: false
            })
          } else if (img.uid) {
            // 新上传图片
            imageIds.push(img.uid.toString())
            processedData.progressImages.push(img)
          }
        })
      }
      processedData.progressPicture = imageIds.join(',')
      this.$emit('submit', processedData)
      this.showDialog = false
    },

    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        // 更新图片列表
        this.form.progressImages = fileList.map((file) => {
          if (file.response && file.response.data) {
            return {
              filePath: file.response.data,
              url: `${STATIC_FILE_URL}${file.response.data}`,
              isUploaded: true
            }
          }
          return {
            url: file.url,
            raw: file.raw,
            isUploaded: false
          }
        })
      } else {
        this.$message.error(response.msg || '上传失败')
      }
    },

    handleUploadError(err) {
      this.$message.error('上传失败')
    },

    handleRemove(file, fileList) {
      this.form.progressImages = fileList.map((file) => {
        if (file.response && file.response.data) {
          return {
            filePath: file.response.data,
            url: `${STATIC_FILE_URL}${file.response.data}`,
            isUploaded: true
          }
        }
        return {
          url: file.url,
          raw: file.raw,
          isUploaded: false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// @import '~@/assets/css/form.scss';
.add-wrap {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 10px;
  overflow-y: auto;

  .body {
    flex: 1;
    padding-bottom: 100px;
    overflow-y: auto;
  }

  .tabs {
    width: 100%;
    height: 50px;
    border-bottom: 1px solid #f1f1f1;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    &-item {
      display: flex;
      align-items: center;
      justify-content: center;
      min-width: 200px;
      height: 100%;
      font-size: 16px;
      font-weight: 500;
      color: #4c565c;
      position: relative;
      cursor: pointer;

      &::before {
        position: absolute;
        content: ' ';
        right: 0;
        top: 19px;
        width: 1px;
        height: 12px;
        background: #d0d8e1;
      }

      &:last-child {
        &::before {
          display: none;
        }
      }

      &.active {
        color: #497fa3;

        &::after {
          position: absolute;
          content: ' ';
          bottom: 0;
          left: 86px;
          width: 26px;
          height: 3px;
          background: #497fa3;
          border-radius: 2px;
        }
      }
    }
  }

  .line {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 60px;
    background: #fff;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10;
  }

  .save-btn {
    background: #497fa3;
    border: 1px solid #497fa3;
    width: 104px;
    color: white;
    font-size: 14px;
    width: 104px;
    height: 34px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
